如何实现一个元素的拖拽效果,使用原生的js实现,习惯了jquery的同学们,你们自己写了吗?N久使用mvvm框架,不写jquery的东西,感觉自己完全不会了。
话不多说,直接上code。本例子以简单的div为例子。
html
<div id="div">我是一个可以退拽的div</div>
css
div {
position: fixed;
left: 0;
top: 0;
width: 100px;
height: 100px;
background: #999;
padding: 10px;
cursor: pointer;
}
javascript
window.onload = funtion() {
const div = document.getElementById('div');
let initPosition = {};
div.addEventListener('mousedown', onMousedown);
function onMousedown(event) {
const { pageX, pageY } = event;
initPosition = getPosition();
document.addEventListener('mousemove', omMousemove);
document.addEventListener('mouseup', onMouseUp);
}
function omMousemove(event) {
const { pageX, pageY } = event;
const { left, top} = calcPosition(pageX, pageY);
div.style.cssText = `left:${left}px;top:${top}px;`;
}
function onMouseUp(event) {
document.removeEventListener('mousemove', onMouseMove);
}
function calcPosition(pageX, pageY) {
const { left, top, scrollLeft, maxCriticalX, maxCriticalY } = initPosition;
let x = pageX - left;
let y = pageY - top;
if (x <= scrollLeft) {
x = scrollLeft;
}
if (x >= maxCriticalX) {
x = maxCriticalX;
}
if (y >= maxCriticalY) {
y = maxCriticalY;
}
if ( y<=0 || maxCriticalY < 0) {
y = 0;
}
return {
left: x,
top: y
};
}
function getPosition() {
const { left, top, width, height } = div.getBoundingClientRect();
const { scrollLeft, scrollTop } = document.body;
const maxCriticalX = scrollLeft + innerWidth - width;
const maxCriticalY = scrollTop + innerHeight - height;
return {
left,
top,
scrollLeft,
maxCriticalX,
maxCriticalY
};
}
};
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。